<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\score\Exchange;
use app\common\model\score\Goods;
use app\common\model\ScoreLog;
use app\common\model\User;
use app\common\model\Address;
use think\Db;
use think\Config;

/**
 * 赏金广告接口
 */
class Score extends Api
{
    protected $noNeedLogin = ['getAdList', 'getAdInfo'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     */
    public function index()
    {
        $this->success('', ['welcome' => '123']);
    }

    /*
     * 积分记录
     */
    public function scoreList(){
        $user_id = $this->auth->getUserinfo()['id'];
        
        $where['user_id'] = $user_id;
        $field = '`before`, `after`, score, memo, createtime';
        $order = 'createtime DESC';
        $scorelist = ScoreLog::field($field)
            ->where($where)
            ->order($order)
            ->paginate()
            ->toArray();

        $score_list_arr = array();
        
        foreach($scorelist['data'] as $key => $val){
            $scorelist['data'][$key]['score'] = $val['score'] < 0 ? $val['score'] : '+'.$val['score']; 
            $scorelist['data'][$key]['createtime_text'] = date('H:i:s', $val['createtime']);
            $scorelist['data'][$key]['createtime_date'] = date('Y-m-d', $val['createtime']);
        }
        
        $this->success('积分记录', $scorelist);  

    }

    /*
     * 积分商品列表
     */
    public function scoreGoodsList(){
        $field = 'id, name, score, imageurl, sale_num';
        $goods_list = Goods::field($field)->order('createtime DESC')->paginate()->each(function($item){
            $item->imageurl = cdnurl($item->imageurl);
        });

        $this->success('积分商品', $goods_list);  
    }


    /*
     * 积分商品详情
     */
    public function scoreGoodsInfo(){
        $id = input('id/d', 0);
        $field = 'id, name, score, imageurl, sale_num, content, createtime';
        $goods_info = Goods::where(array('id'=>$id))->field($field)->order('createtime DESC')->find();
        if(!$goods_info){
            $this->error("商品不存在");
        }
        $goods_info->imageurl = cdnurl($goods_info->imageurl);
        $this->success('积分商品', $goods_info);  
    }

    /*
     * 兑换商品
     */
    public function exchangeGoods(){
        $user_info = $this->auth->getUserinfo();
        $id = input('id/d', 0);
        $field = 'id, name, score, imageurl, sale_num, content, createtime, stock,is_real';
        $goods_info = Goods::where(array('id'=>$id))->field($field)->order('createtime DESC')->find();

        if($goods_info['stock'] <= 0){
            $this->error('库存不足');
        }
        if($user_info['score'] < $goods_info['score']){
            $this->error('积分不足');
        }

        $address = null;

        if($goods_info['is_real']>0){
            #检测是否有地址
            $address = Address::where('user_id', $user_info['id'])->order('is_default desc')->find();

            if(!$address){
                $this->error('请先在个人中心添加默认地址');
            }
        }

        //添加兑换记录
        $add_data['user_id'] = $user_info['id'];
        $add_data['address_id'] = $address ? $address['id'] : 0;
        $add_data['score_goods_id'] = $id;
        $add_data['score_amount'] = $goods_info['score'];
        $add_data['num'] = 1;
        Db::startTrans();
        $add_info = Exchange::create($add_data);
        //商品兑换数量+1
        $update_data['sale_num'] = $goods_info['sale_num'] + 1;
        $update_data['stock'] = $goods_info['stock'] - 1;
        $update_goods = Goods::where(array('id'=>$id))->update($update_data);
        //修改积分，积分记录
        User::score((0-$goods_info['score']), $user_info['id'], '积分兑换商品');
        if(!$add_info || $update_goods === false){
            Db::rollback();
            $this->error('操作失败');
        }else{
            Db::commit();
            $this->success('操作成功');
        }
    }

    /*
     * 兑换记录
     */
    public function exchangeList(){
        $user_id = $this->auth->getUserinfo()['id'];
        $where['user_id'] = $user_id;
        $exch_list = Exchange::where($where)->order('createtime DESC')
            ->paginate()
            ->each(function($item, $key){
                $score_goods = Goods::where(array('id'=>$item->score_goods_id))->field('name, imageurl')->find();
                $item->name = $score_goods['name'];
                $item->imageurl = cdnurl($score_goods['imageurl']);
            });
        $this->success('兑换记录', $exch_list);
    }
   
}
